//
//  HomeTableViewController.swift
//  WBDemo
//
//  Created by Meng on 16/12/14.
//  Copyright © 2016年 demo. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage
import Dispatch
import MJRefresh

class HomeTableViewController: BaseTableViewController {
    
    var statuses: [HomeViewModel]?
    private var cacheRowHeight = [String: CGFloat]()
    private var statusFlag = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin {
            visitorView?.setupInfoWithVisitorView(imageName: nil, title: "关注一些人，回这里看看有什么惊喜")
        } else {
            setupNav()
            setupTableView()
            setupRefreshControl()
            setupNotification()
            setupTipView()
            loadStatusData()
        }
        
    }
    
    // MARK: - 内部方法
    
    @objc private func loadStatusData() {
        var sinceid = statuses?.first?.status?.idstr ?? "0"
        var maxid = "0"
        if statusFlag {
            sinceid = "0"
            maxid = statuses?.last?.status?.idstr ?? "0"
            statusFlag = false
        }
        NetworkTool.shareInstance.loadStatuses(since_id: sinceid, max_id: maxid) { (dictArr: [[String : AnyObject]]?, error: Error?) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "获取微博数据失败")
            } else {
                // 将字典转为模型
                guard let arr = dictArr else {
                    return
                }
                var models = [HomeViewModel]()
                for dict in arr {
                    let status = Status(dict: dict)
                    let vm = HomeViewModel(status: status)
                    models.append(vm)
                }
                if sinceid != "0" {
                    self.statuses = models + self.statuses!
                } else if maxid != "0" {
                    self.statuses = self.statuses! + models
                }else {
                    self.statuses = models
                }
//                for s in self.statuses! {
//                    MYLog(s.status?.idstr)
//                }
                self.cacheImages(viewModels: models)
                
                self.showTipView(count: models.count)
                
                self.refreshControl?.endRefreshing()
            }
        }
    }
    // 缓存图片
    private func cacheImages(viewModels: [HomeViewModel]) {
        // 创建group队列
        let group = DispatchGroup()
        for viewModel in viewModels {
            guard let urls = viewModel.thumbnail_urls else {
                continue
            }
            for url in urls {
                // 将当前的下载操作加入到group队列
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: SDWebImageOptions(rawValue:0), progress: nil, completed: { (image: UIImage?, error: Error?, _, _, _) in
                    // 将当前的下载操作从group队列中移除
                    group.leave()
                })
            }
        }
        // 所有的下载操作完成后的监听
        group.notify(queue: DispatchQueue.main) {
            self.tableView.reloadData()
        }
    }
    
    private func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(leftDidClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(rightDidClick))
        
        navigationItem.titleView = titleButton
        
        navigationController?.navigationBar.isTranslucent = false
        
    }
    
    private func setupTableView() {
//        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
    }
    
    private func setupRefreshControl() {
        refreshControl = CustomRefreshControl()
        refreshControl?.addTarget(self, action: #selector(loadStatusData), for: UIControlEvents.valueChanged)
    }
    
    private func setupNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(titleChange), name: NSNotification.Name(rawValue: PopoverPresentationManagerDidPresented), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(titleChange), name: NSNotification.Name(rawValue: PopoverPresentationManagerDidDismissed), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(showPhotoBrowser(noti:)), name: NSNotification.Name.init(ShowPhotoBrowserController), object: nil)
    }
    
    private func setupTipView() {
        navigationController?.view.insertSubview(tipLabel, belowSubview: navigationController!.navigationBar)
    }
    
    private func showTipView(count: Int) {
        
        tipLabel.text = (count == 0) ? "没有更多数据" : "\(count)条新微博"
        UIView.animate(withDuration: 1.0, animations: { 
            self.tipLabel.transform = CGAffineTransform.init(translationX: 0, y: 44)
        }) { (_) in
            UIView.animate(withDuration: 1.0, delay: 2.0, options: UIViewAnimationOptions.init(rawValue: 0), animations: {
                self.tipLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                
            })
        }
        
    }
    
    // MARK: - 懒加载
    
    private lazy var presentationManager : PopoverPresentationManager = PopoverPresentationManager()
    
    private lazy var titleButton : TitleButton = {
        let btn = TitleButton()
        let title = UserAccount.readUserAccount()?.screen_name
        btn.setTitle(title, for: .normal)
        btn.addTarget(self, action: #selector(titleButtonClick(button:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.orange
        label.textColor = UIColor.white
        label.textAlignment = NSTextAlignment.center
        label.frame = CGRect(x: 0, y:20, width: UIScreen.main.bounds.width, height: 44)
        return label
    }()
    
    
    // MARK: - 通知
    
    @objc private func titleChange() {
        titleButton.isSelected = !titleButton.isSelected
    }
    
    @objc private func showPhotoBrowser(noti: Notification) {
        guard let urls = noti.userInfo?["bmiddle_urls"] as? [URL] else {
            return
        }
        guard let indexPath = noti.userInfo?["indexPath"] as? IndexPath else {
            return
        }
        guard let pcView = noti.object as? PictureView else {
            return
        }
        let sb = UIStoryboard(name: "PhotoBrowser", bundle: nil)
        guard let photoBrowserVC = sb.instantiateInitialViewController() as? PhotoBrowserViewController else {
            return
        }
        photoBrowserVC.bmiddle_urls = urls
        photoBrowserVC.indexPath = indexPath
        // 自定义转场动画
        let pbpresentationController = PhotoBrowserPresentationController.init(presentedViewController: photoBrowserVC, presenting: self)
        pbpresentationController.indexPath = indexPath
        pbpresentationController.browserDelegate = pcView
        photoBrowserVC.transitioningDelegate = pbpresentationController
        photoBrowserVC.modalPresentationStyle = UIModalPresentationStyle.custom
        present(photoBrowserVC, animated: true, completion: nil)
    }
    
    
    // MARK: - clickAction
    
    @objc private func titleButtonClick(button: TitleButton) {
        
        let sb = UIStoryboard(name: "Popover", bundle: nil)
        
        let menuvc = sb.instantiateInitialViewController()
        
        guard let presentvc = menuvc else {
            return
        }
        // 自定义转场动画
        presentvc.transitioningDelegate = presentationManager
        presentvc.modalPresentationStyle = UIModalPresentationStyle.custom
        
        present(presentvc, animated: true, completion: nil)
        
    }
    
    @objc private func leftDidClick() {
        MYLog("")
    }
    
    @objc private func rightDidClick() {
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        guard let vc = sb.instantiateInitialViewController() else {
            return
        }
        present(vc, animated: true, completion: nil)
    }
    
    // MARK: - UITableViewDataSource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let vm = statuses![indexPath.row]
        let identifier = (vm.status?.retweeted_status != nil) ? "forwardCell" : "homeCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! HomeCell
        cell.viewModel = vm
        if indexPath.row == (statuses!.count - 1) {
            statusFlag = true
            loadStatusData()
        }
        return cell
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let viewModel = statuses![indexPath.row]
        guard let height = cacheRowHeight[(viewModel.status?.idstr)!] else {
            let identifier = (viewModel.status?.retweeted_status != nil) ? "forwardCell" : "homeCell"
            let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! HomeCell
            let tempH = cell.calculateRowHeight(viewModel: viewModel)
            cacheRowHeight[(viewModel.status?.idstr)!] = tempH
            return tempH
        }
        return height
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        cacheRowHeight.removeAll()
    }
    
}

